package com.xopencode.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mcb
 * @date 2022/5/25
 * @apiNote lock版本生产者和消费者,按顺序通知 a->b->c
 */
public class LockDemo2 {
    public static void main(String[] args) {

        Data3 data = new Data3();
        new Thread(() -> {
            data.runA();
        }, "A").start();

        new Thread(() -> {
            data.runB();
        }, "B").start();

        new Thread(() -> {
            data.runC();
        }, "C").start();
    }
}

class Data3{
    //资源类
    private Lock lock=new ReentrantLock();
    private Condition a = lock.newCondition();
    private Condition b = lock.newCondition();
    private Condition c = lock.newCondition();
    private int number = 1;

    public void runA(){
        lock.lock();
        try {
            while (number != 1){
                a.await();
            }
            System.out.println(Thread.currentThread().getName()+",AAAAA");
            number = 2;
            b.signal(); //唤醒b
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void runB(){
        lock.lock();
        try {
            while (number != 2){
                b.await();
            }
            System.out.println(Thread.currentThread().getName()+",BBBB");
            number = 3;
            c.signal(); //唤醒b
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void runC(){
        lock.lock();
        try {
            while (number != 3){
                c.await();
            }
            System.out.println(Thread.currentThread().getName()+",CCCC");
            number = 1;
            a.signal(); //唤醒b
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}

